<template>
  <div class="app-container">
    <el-dialog v-loading="loading" :visible.sync="permissionsFormVisible" :before-close="handleClose" title="分配角色权限">

      <el-tree
        ref="tree"
        :data="data5"
        :allow-drop="allowDrop"
        :default-expand-all="false"
        :props="defaultProps"
        :expand-on-click-node="false"
        :default-checked-keys="codePermId"
        :render-content="renderContent"
        draggable
        render-after-expand
        node-key="customId"
        show-checkbox
        @node-drop="handleDrop"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="getCheckedNodes">确认分配</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchRoleMenuList, grantPermission, fetchRoleView } from '@/api/system'
import { codeValidation } from '@/methods/codeValidation'

export default {
  name: 'Tree',
  props: ['permissionRole'],

  data() {
    return {
      // data5: JSON.parse(JSON.stringify(data)),
      permissionsFormVisible: true,
      // 所有权限
      data5: [],
      // 用户已有的权限ID
      codePermId: [],

      defaultProps: {
        children: 'children',
        label: 'i18nName'
      },

      loading: false

    }
  },
  computed: {
    classObject(node, data) {
      console.log(node.label)
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    }
  },
  created() {
    this.getMenuList()
  },
  methods: {

    // 菜单列表
    getMenuList() {
      var self = this
      this.loading = true
      fetchRoleMenuList().then(response => {
        var menuTree = response.data.menuTree
        menuTree.forEach((val) => {
          self.customId(val)
        })
        menuTree.forEach((val) => {
          self.pushPermissions(val)
        })
        this.data5 = menuTree

        this.$nextTick(function() {
          self.getRolePerm()
        })
      })
    },

    // 给文件夹 添加一个自定义字段 customId
    customId(node) {
      var self = this
      node['customId'] = 'c' + node.id
      if (node.children) {
        if (node.children.length > 0) {
          var ch = node.children
          ch.forEach((val) => {
            self.customId(val)
          })
        }
      }
    },

    // 将 Permissions( 权限 ) 放到 children 中
    pushPermissions(node) {
      var self = this

      if (node.permissions) {
        var dd = node.permissions
        dd.forEach((val) => {
          // 用来在移动的时候判断是否可以移动
          val['i18nName'] = val.i18nPermName
          // 用来在移动的时候判断是否可以移动
          val['isPermissions'] = true
          val['customId'] = 'p' + val.id
          node.children.push(val)
        })
      }
      if (node.children) {
        if (node.children.length > 0) {
          var ch = node.children
          ch.forEach((val) => {
            self.pushPermissions(val)
          })
        }
      }
    },

    // 获取某个角色拥有的权限
    getRolePerm() {
      var data = {
        id: this.permissionRole.roleId
      }
      fetchRoleView(data).then(response => {
        var self = this
        var aPerm = response.data.role.permissions
        var tempData = []
        aPerm.forEach((value) => {
          tempData.push('p' + value.id)
        })
        this.codePermId = tempData

        this.loading = false
      })
    },

    // 返回选中的节点 加 确认分配
    /* 拿到所有选中的节点 包括父节点
      *  然后根据 节点数据中是否有 children 来判断 是否为父节点
      *  如果长度 等于 0 则 说明是 子节点 并将其 ID 记录到临时变量 tempChechedId
      * */
    getCheckedNodes() {
      var self = this
      var permissionArr = self.$refs.tree.getCheckedNodes()
      var tempChechedId = []

      permissionArr.forEach((value) => {
        if (value.children) {
          console.log('11')
        } else {
          tempChechedId.push(value.id)
        }
      })

      var data = {
        id: self.permissionRole.roleId,
        permissionIds: tempChechedId.join()
      }
      grantPermission(data).then(response => {
        var code = '0'
        var content = response.content
        self.$emit('cancel')
        codeValidation(code, content, self)
      })
    },

    // 判断目标节点是否可以放置
    /* 通过 目标节点 的 childern 长度是否为 0  来判断
      *  当 childern 长度 为 0 , 则为不能拖动
      * */
    allowDrop(draggingNode, dropNode, type) {
      if (dropNode.data.isPermissions) {
        return false
      } else {
        return true
      }
    },

    // 自定义内容
    renderContent(h, { node, data, store }) {
      return (
        <span class='custom-tree-node'>
          <span>{node.label}</span>
          <span>
          </span>
        </span>)

      // <el-button size="mini" type="text" on-click={ () => this.append(data) }>Append</el-button>
      // <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }>Delete</el-button>
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('拖拽的节点: ', draggingNode)
      console.log('放置的节点: ', dropNode)
    },

    append(data) {
      // console.log('当前data为：', data)
      const newChild = { id: id++, label: 'testtest', children: [] }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
    },

    remove(node, data) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },

    // 取消
    cancel() {
      this.$emit('cancel')
    },

    handleClose() {
      this.$emit('cancel')
    },

    rihgtClick(event, object, value, element) {
      if (value.level == 1) {
        this.menuVisible = true
        const menu = document.querySelector('#menu')
        /* 菜单定位基于鼠标点击位置 */
        menu.style.left = event.clientX + 20 + 'px'
        menu.style.top = event.clientY - 10 + 'px'
      }
      console.log('右键被点击的event:', event)
      console.log('右键被点击的object:', object)
      console.log('右键被点击的value:', value)
      console.log('右键被点击的element:', element)
    }
  }
}
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>

